<template>
  <div class="container">
    <el-form :model="form" :rules="rules" ref="form" :inline="true">
      <el-row type="flex" class="form_row">
        <el-col :span="18">
          <el-form-item>
            <el-input v-model="form.name" placeholder="请输入企业名称/职位名称" style="width:250px;"></el-input>
          </el-form-item>
          <el-form-item>
            <el-select v-model="form.status" placeholder="请选择审核状态">
              <el-option label="等待审核" :value="0"></el-option>
              <el-option label="审核通过" :value="1"></el-option>
              <el-option label="已下线" :value="3"></el-option>
              <el-option label="审核未通过" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布时间" class="create_time">
            <el-date-picker v-model="form.startTime" type="date" value-format="yyyy-MM-dd" placeholder="发布时间范围">
            </el-date-picker>
          </el-form-item>
          <el-form-item prop="endTime" class="create_time" label="至">
            <el-date-picker v-model="form.endTime" type="date" value-format="yyyy-MM-dd" placeholder="发布时间范围">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6" style="text-align:right;">
          <el-form-item class="btn_box">
            <el-button type="primary" @click="search">查询</el-button>
            <el-button type="primary" @click="reset">重置</el-button>
            <el-button type="primary" @click="addPosition">代发职位</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="auth_box">
      <el-button @click="jobExamine()" type="info">审核职位</el-button>
      <el-button @click="refresTime()" type="info">刷新</el-button>
      <el-button @click="delFiles()" type="info">删除</el-button>
    </div>
    <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%" align="center"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="name" label="职位名称" show-overflow-tooltip></el-table-column>
      <el-table-column prop="companyName" label="发布公司" show-overflow-tooltip></el-table-column>
      <el-table-column label="审核状态" width="90" prop="status">
        <template slot-scope="scope">
          <span v-if="scope.row.status == 0" class="reject">等待审核</span>
          <span v-if="scope.row.status == 1" class="success">审核通过</span>
          <span v-if="scope.row.status == 2" class="reject">审核未通过</span>
          <span v-if="scope.row.status == 3">已下线</span>
        </template>
        <!-- <template slot-scope="scope">
          <span class="auth_span">{{scope.row.status | getName}}</span>
        </template> -->
      </el-table-column>
      <el-table-column label="发布时间" show-overflow-tooltip>
        <template slot-scope="scope">{{ scope.row.createTime.slice(0,10) }}</template>
      </el-table-column>
      <el-table-column label="到期时间" show-overflow-tooltip>
        <template slot-scope="scope">{{ scope.row.expireTime.slice(0,10) }}</template>
      </el-table-column>
      <el-table-column label="刷新时间" show-overflow-tooltip>
        <template slot-scope="scope">{{ scope.row.refreshTime.slice(0,10) }}</template>
      </el-table-column>
      <el-table-column label="职位类型" prop="jobTypeText"></el-table-column>
      <el-table-column label="退役军人职位" show-overflow-tooltip>
        <template slot-scope="scope">{{ scope.row.isVeteran ? '是' : '否'}}</template>
      </el-table-column>
      <el-table-column label="操作" width="130">
        <template slot-scope="scope">
          <!-- <el-button @click="handleClick(scope.row)" type="text" size="small">日志</el-button> -->
          <el-button type="text" size="small" @click="toJobAlter(scope.row)">修改</el-button>
          <!-- <el-button type="text" size="small">管理</el-button> -->
          <el-button v-if="!scope.row.isVeteran" type="text" size="small" @click="pushVeterans(scope.row)">退役军人推送
          </el-button>
          <el-button v-else type="text" size="small" @click="cancelVeterans(scope.row)">取消退役军人</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="page" :page-sizes="[10,30,60,100,200,300]" :page-size="size"
        layout="prev, pager, next, jumper, sizes, total" :total="total"></el-pagination>
    </div>
    <el-dialog :visible.sync="dialogVisible" width="50%" class="elDialog">
      <p slot="title" class="elDialog-header">
        <span>批量审核</span>
      </p>
      <el-form :model="examine" ref="examine" :rules="rules">
        <el-form-item label="审核结果：" prop="status">
          <el-radio-group v-model="examine.status">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">不通过</el-radio>
            <el-radio :label="0">待定</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核不通过原因：" prop="reason" v-if="examine.status===2">
          <el-input type="textarea" v-model="examine.reason"></el-input>
        </el-form-item>
        <el-form-item class="mid_box">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="onSubmit">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 推送退役军人弹框 -->
    <el-dialog :visible.sync="veteransVisible" width="30%" class="elDialog veteransDialog" :before-close="handleClose">
      <p slot="title" class="elDialog-header">
        <span>退役军人推送</span>
      </p>
      <el-form :model="veteransForm" :inline="true" ref="veteransForm" :rules="veteransRules">
        <el-form-item label="推送排序" prop="orderNo">
          <el-input v-model.number="veteransForm.orderNo"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveVeterans('veteransForm')">确 定</el-button>
        <el-button @click="resetForm('veteransForm')">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { pageList, refresh, jobDelete, examine, addInsert, deleteVeterans, deleteNotexcludeById } from '../../../../api/jobList';
import bus from '../../../common/bus'
export default {
  name: 'jobList',
  data () {
    var checkStartTime = (rule, value, callback) => {
      if (this.form.startTime) {
        let startTime = parseInt(this.form.startTime.replace(/-/g, ''));
        let endTime = parseInt(value.replace(/-/g, ''));
        if (startTime > endTime) {
          callback(new Error('请输入正确时间范围！'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    // 推送排序校验
    var checkOrderNo = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入推送排序'));
      } else if (typeof value != 'number') {
        callback(new Error('请输入数字'));
      } else if (value < 1) {
        callback(new Error('推送排序最小不得小于1'));
      } else if (!/(^[1-9]\d*$)/.test(value)) {
        callback(new Error('推送排序必须是1-300的整数'));
      } else if (value > 300) {
        callback(new Error('推送排序最大不得大于300'));
      } else {
        callback();
      }
    };
    return {
      dialogVisible: false,
      examine: {
        status: '',
        reason: ''
      },
      selection: [],
      total: 0,
      page: 1,
      size: 10,
      form: {
        name: '',
        status: '',
        startTime: '',
        endTime: ''
      },
      rules: {
        endTime: [{ validator: checkStartTime }],
        status: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
        reason: [{ required: true, message: '请选择审核结果', trigger: 'change' }]
      },
      tableData: [],
      veteransVisible: false,  // 控制退役军人弹框
      veteransForm: {    // 退役军人form
        jobId: '',
        companyId: '',
        orderNo: '',
      },
      veteransRules: {
        orderNo: [{ type: 'number', required: true, validator: checkOrderNo }]
      }
    };
  },
  created () {
    if (this.$route.query.status == 0) {
      this.form.status = Number(this.$route.query.status)
    }

    this.getPageList();
  },
  watch: {
    '$route.fullPath': function (val, oldVal) {
      this.$nextTick(() => {
        if (this.$route.query.status == 0) {
          this.form.status = Number(this.$route.query.status)
          this.getPageList();
        }
      })
    }
  },
  filters: {
    getName (val) {
      switch (val) {
        case 3:
          return '已下线';
        case 1:
          return '认证通过';
        case 2:
          return '认证未通过';
        default:
          return '等待认证';
      }
    }
  },
  methods: {
    search () {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.getPageList();
        } else {
          this.$message.error(`无法识别创建时间范围!`);
        }
      });
    },
    getPageList () {
      let condition = [
        { column: 'company_job_name', type: '', value: this.form.name },
        { column: 'status', type: 'eq', value: this.form.status },
        { column: 'create_time', type: 'dtge', value: this.form.startTime },
        { column: 'create_time', type: 'dtle', value: this.form.endTime },
        { "column": "include", "type": "", "value": "CN,D" }
      ];
      let file = new FormData();
      file.append('page', this.page);
      file.append('size', this.size);
      file.append('condition', JSON.stringify(condition));
      file.append('sort', JSON.stringify([{ column: 'update_time', type: 'desc' }]));
      pageList(file).then(data => {
        if (data.success) {
          this.tableData = data.data.records;
          this.total = data.data.total;
        } else {
          this.$message.error(`${data.msg}`);
        }
      });
    },
    reset () {
      this.form = {};
      this.page = 1;
      this.size = 10;
      this.getPageList();
    },
    handleClick (row) {
      this.$router.push({ path: '/log', query: { id: row.companyId } });
    },
    handleSelectionChange (selected) {
      console.log(selected);
      this.selection = selected;
    },
    onSubmit () {
      this.$refs.examine.validate(valid => {
        if (valid) {
          console.log(this.selection);
          let file = new FormData();
          file.append('id', this.selection.map(item => item.id).join(','));
          file.append('status', this.examine.status);
          file.append('reason', this.examine.reason);
          file.append('companyId', this.selection.map(item => item.companyId).join(','));
          examine(file).then(data => {
            console.log(data);
            if (data.success) {
              this.$message.success(`审核完成`);
              this.getPageList();
            } else {
              this.$message.error(`${data.msg}`);
            }
            this.dialogVisible = false;
          });
        }
      });
    },
    refresTime () {
      if (this.selection.length < 1) {
        this.$message.error('请选择需要刷新的职位!');
      } else {
        let file = new FormData();
        file.append('id', this.selection.map(item => item.id).join(','));
        refresh(file).then(data => {
          console.log(data);
          if (data.success) {
            this.getPageList();
            this.$message.success('刷新成功');
          } else {
            this.$message.error(`${data.msg}`);
          }
        });
      }
    },
    // 审核职位
    jobExamine () {
      if (this.selection.length < 1) {
        this.$message.error('请选择需要审核的职位!');
      } else {
        this.dialogVisible = true;
      }
    },
    delFiles () {
      if (this.selection.length < 1) {
        this.$message.error('请选择想要删除的职位!');
      } else {
        this.$confirm('您要删除职位，删除后不可恢复，是否确定操作？', '信息提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          callback: action => {
            console.log(action);
            if (action === 'confirm') {
              let file = new FormData();
              file.append('id', this.selection.map(item => item.id).join(','));
              jobDelete(file).then(data => {
                console.log(data);
                if (data.success) {
                  this.getPageList();
                  this.$message.success('删除成功');
                } else {
                  this.$message.error(`${data.msg}`);
                }
              });
            }
          }
        });
      }
    },
    toJobAlter (row) {
      console.log(row, '修改')
      // this.$router.push({ path: '/jobAlter', query: { id: row.id } });
      bus.$emit('openTags', { fullPath: `/jobAlter?id=${row.id}`, meta: { title: row.name } })
    },
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`);
      this.size = val;
      this.getPageList();
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`);
      this.page = val;
      this.getPageList();
    },
    // 退役军人推送
    pushVeterans (row) {
      this.veteransVisible = true;
      this.veteransForm.jobId = row.id;
      this.veteransForm.companyId = row.companyId;
      let query = new FormData();
      query.append('jobId', row.id);
      query.append('companyId', row.companyId);
      // 根据公司ID和职位ID查询数据(不过滤已删除)
      deleteNotexcludeById(query).then(res => {
        if (res.success) {
          if (res.data) {
            this.veteransForm.orderNo = res.data.orderNo;
          }
        } else {
          this.$message.error(`${res.msg}`)
        }
      })
    },
    // 取消退役军人
    cancelVeterans (row) {
      let query = new FormData();
      query.append('jobId', row.id);
      query.append('companyId', row.companyId);
      deleteVeterans(query).then(res => {
        if (res.success) {
          this.$message.success('取消退役军人成功!')
          this.getPageList()
        } else {
          this.$message.error(`${res.msg}`)
        }
      })
    },
    // 保存推送的退役军人
    saveVeterans (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let query = new FormData();
          query.append('jobId', this.veteransForm.jobId);
          query.append('companyId', this.veteransForm.companyId);
          query.append('orderNo', this.veteransForm.orderNo);
          addInsert(query).then(res => {
            if (res.success) {
              this.$message.success('推送退役军人成功')
              this.getPageList()
              this.handleClose()
            } else {
              this.$message.error(`${res.msg}`)
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 关闭弹框回调
    handleClose () {
      this.$refs.veteransForm.resetFields()
      this.veteransVisible = false;
    },
    // 清空表单
    resetForm (formName) {
      this.$refs[formName].resetFields();
      this.veteransVisible = false;
    },
    // 代发职位
    addPosition () {
      this.$router.push('/addPosition')
    }
  }
};
</script>

<style scoped>
.el-form {
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.el-form .create_time {
    width: 212px !important;
}
.el-form .create_time /deep/ .el-date-editor {
    width: 144px;
}
.el-form .create_time /deep/ .el-date-editor /deep/ .el-input__inner {
    width: 144px;
}
.el-form .create_time /deep/ .el-form-item__content {
    display: inline-block;
}
.el-form .form_box .el-form-item {
    display: inline-block;
    margin-right: 30px;
}
.el-form .form_box .date_box {
    display: inline-block;
}
.el-form .form_box .date_box .el-form-item .el-date-editor {
    width: 140px;
}
.el-form .el-date-editor /deep/ .el-input__inner {
    width: 140px;
}
.el-form .btn_box .el-button {
    width: 85px;
}
.el-table {
    /* height: 82%; */
    min-height: 400px;
    max-height: 555px;
}

.el-table /deep/ td,
.el-table /deep/ th {
    text-align: center;
}
.el-table /deep/.el-table__empty-block {
    width: 99.5% !important;
    height: 98% !important;
    min-height: 350px;
}
.el-table /deep/.el-table__empty-text {
    font-size: 18px;
}
.auth_box {
    margin-bottom: 20px;
    text-align: right;
}
.auth_box .el-button {
    width: 100px;
}
.page {
    width: 100%;
    height: 40px;
    background: #ffffff;
    text-align: center;
    padding-top: 20px;
}
.companyList /deep/ .el-table__body-wrapper {
    height: 655px;
}
.el-dialog .el-form {
    flex: unset;
    display: block;
}
.el-dialog .el-form .el-form-item {
    display: block;
    margin-bottom: 20px;
}
.el-dialog .el-form /deep/ .el-form-item__label {
    width: 150px;
}
.el-dialog .el-form /deep/ .el-textarea {
    position: unset;
    width: 300px;
    height: 100px;
}
.el-dialog .el-form /deep/ .el-textarea textarea {
    width: 300px;
    height: 100px;
}
.el-dialog .el-form /deep/ .el-button {
    width: 100px;
    margin-right: 20px;
}
.el-dialog .mid_box {
    text-align: center;
}
/* 退役军人弹框样式*/
.veteransDialog {
    /* border: 1px solid red; */
}
.veteransDialog /deep/ .el-form .el-form-item__label {
    width: auto;
}
.form_row {
    width: 100%;
}
</style>